package com.probiz.estoresa.system.web.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.probiz.estore.common.model.system.MsgTemplate;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.core.model.BaseObject;
import com.probiz.estore.system.service.MsgTemplateManager;
import com.probiz.estore.system.util.MsgTemplateConstants;

public class MsgTemplateController extends GenericStoreAdminController<MsgTemplate> {
	 private MsgTemplateManager msgTemplateManager = null;

	    public void setMsgTemplateManager(MsgTemplateManager inMgr) {
	        this.msgTemplateManager = inMgr;
	    }

		/*
		 * (non-Javadoc)
		 * 
		 * @see com.probiz.estore.core.controller.GenericController#getEntityName(java.lang.Object)
		 */
		@Override
		protected String getEntityName(MsgTemplate entity) {
			return entity.getMsgTemplateName();
		}


		/*
		 * (non-Javadoc)
		 * 
		 * @see com.probiz.estore.core.controller.BaseController#initController()
		 */
		@Override
		protected void initController() throws Exception {
			mgr = msgTemplateManager;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see com.probiz.estore.core.controller.GenericController#preSave(javax.servlet.http.HttpServletRequest,
		 *      java.lang.Object, org.springframework.validation.BindException)
		 */
		@Override
		protected void preSave(HttpServletRequest request, MsgTemplate entity, BindException errors) {
		}
		
		public ModelAndView search(HttpServletRequest request, HttpServletResponse response) {
			//Store store = StoreUtil.getCurrentStore(request);
			List list = msgTemplateManager.getGroupByTemplate(null, MsgTemplateConstants.MSGTEMPLATE_ISSTOREADMIN);
			List defaultList = msgTemplateManager.getGroupByTemplate(null, MsgTemplateConstants.MSGTEMPLATE_ISSTOREADMIN);
			List results  = new ArrayList();
			results.addAll(defaultList);
			String key = "templateItem";
			for(int i=0; i<list.size(); i++){
				Map map = (HashMap)list.get(i);
				for(int n=0; n<defaultList.size(); n++){
					Map map2 = (HashMap)defaultList.get(n);
					if (map.get(key).equals(map2.get(key))){
						results.remove(defaultList.get(n));
					}
				}
			}
			results.addAll(list);
			if (results.size()<=0) {
				results = msgTemplateManager.getGroupByTemplate(null, MsgTemplateConstants.MSGTEMPLATE_ISSTOREADMIN);
			}
			return getModelAndView(listView, listModelName, results);
		}
		
		/**
		 * 重载edit方法，主要是去掉设置导航信息,否则列表页面跳转会有问题，（savedNavAndSearchCriteria(....)），其他处理与框架一致，
		 */
		@Override
		public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
			
			MsgTemplate entity = formBackingObject(request);
			ModelAndView mv = new ModelAndView(formView);
			//if (entity.getStoreId() == null) entity.setMsgTemplateId(null);
			mv.addObject("msgTemplate", entity);
			String temp = entity.getLabelsVariable().replace(";", "；");
			String[] arrayTemp = temp.split("；");
			List list = new ArrayList();
			List tempList = new ArrayList();
			if(null != arrayTemp && arrayTemp.length > 0){
				for(int i = 0;i < arrayTemp.length; i++){
					String[] arryTemp = arrayTemp[i].split("===");
					tempList.add(arryTemp);
					if((i+1)%2 == 0 && i < arrayTemp.length - 1){
						list.add(tempList);
						tempList = new ArrayList();
					}else if(i == arrayTemp.length - 1){
						list.add(tempList);
						tempList = new ArrayList();
					}
				}
			}
			mv.addObject("labelsVariablesList", list);
			return mv;
		}
		
		/**
		 * 批保存
		 * @param request
		 * @param response
		 */
		public ModelAndView multiSave(HttpServletRequest request, HttpServletResponse response) {
			String[] msgTemplateId0 = request.getParameterValues("msgTemplateId0");
			String[] msgTemplateId1 = request.getParameterValues("msgTemplateId1");
			String[] msgTemplateId2 = request.getParameterValues("msgTemplateId2");
			String[] status0 = request.getParameterValues("ck_status0");
			String[] status1 = request.getParameterValues("ck_status1");
			String[] status2 = request.getParameterValues("ck_status2");
			List<MsgTemplate> msgTemplateList = new ArrayList<MsgTemplate>();
			//邮件
			if (msgTemplateId0.length > 0) {
				for (int i = 0; i < msgTemplateId0.length; i++) {
					Short status = new Short(status0[i]);
					if(2 == (short)status){
						status = null;
					}
					MsgTemplate msgTemplate = msgTemplateManager.getById(new Integer(msgTemplateId0[i]));
					
					msgTemplate.setStatus(status);
					msgTemplateList.add(msgTemplate);
					
				}
			}
			//站内
			if (msgTemplateId1.length > 0) {
				for (int i = 0; i < msgTemplateId1.length; i++) {
					Short status = new Short(status1[i]);
					if(2 == (short)status){
						status = null;
					}
					MsgTemplate msgTemplate = msgTemplateManager.getById(new Integer(msgTemplateId1[i]));
					msgTemplate.setStatus(status);
					msgTemplateList.add(msgTemplate);
				}
			}
			//短信
			if (msgTemplateId2.length > 0) {
				for (int i = 0; i < msgTemplateId2.length; i++) {
					Short status = new Short(status2[i]);
					if(2 == (short)status){
						status = null;
					}
					MsgTemplate msgTemplate = msgTemplateManager.getById(new Integer(msgTemplateId2[i]));
					msgTemplate.setStatus(status);
					msgTemplateList.add(msgTemplate);
				}
			}
			if (msgTemplateList.size() > 0) {
				// update batch
				msgTemplateManager.updateBatchEnableMsgTemplates(msgTemplateList);
				String message = getMessage("common.updated.multi");
				saveMessage(request, message);
			}
			// save message
			return new ModelAndView(new RedirectView("msgTemplate.html"));
		}
		
		/**
		 * 保存单个记录的数据，并可以处理应用级的错误信息。在formBackingObject读数据的时候已经加锁，所以可以保证事务和版本控制。
		 * 子类需要实现onSave。
		 * 
		 * @param request
		 * @param response
		 * @return
		 */
		public ModelAndView save(HttpServletRequest request,
				HttpServletResponse response) throws Exception {
			// 取得Form对应的Model
			MsgTemplate entity = formBackingObject(request);
			BindException errors = null;
			try {
				bindReady(entity);
				ServletRequestDataBinder binder = bindAndValidate(request, entity);
				errors = new BindException(binder.getBindingResult());
				// 传给子类的实现，后者可以继续验证和加入错误到errors
				preSave(request, entity, errors);
				if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
					mgr.update(entity);
					postSave(request, entity);
				}
			} catch (ApplicationException e) {
				handleApplicationException(errors, e);
			}

			ModelAndView mav;
			if (errors.hasErrors()) {
				mav = showForm(request, errors);
			} else if (successView != null) {
				mav = getModelAndView(successView, errors.getModel());
			} else {
				mav = getRedirectToActionView("edit", ((BaseObject) entity).getId().toString());
			}
			return mav;
		}
		
		
		
		protected void postSave(HttpServletRequest request, MsgTemplate entity) {
			// 保存操作成功的提示信息
			String msgKey = (isEntityNew(request)) ? "common.added"
					: "common.updated";
			String messageVal = "";
			if(entity.getType() == 0){
				messageVal = entity.getTemplateName()+"邮件模板";
			}else if(entity.getType() == 1){
				messageVal = entity.getTemplateName()+"站内信模板";
			}else{
				messageVal = entity.getTemplateName()+"手机短信模板";
			}
			String message = getMessage(msgKey, new Object[] {
					getEntityTypeMessage(), messageVal });
			saveMessage(request, message);
		}
		
		// 保存前的绑定
		private void bindReady(MsgTemplate entity) {
			if (null == entity.getMsgTemplateId()) {
				entity.setStoreId(null);
			}
			
		}
}
